package com.gitee.zhangchenyan.takin.auth;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import com.gitee.zhangchenyan.takin.common.result.Result;
import com.gitee.zhangchenyan.takin.common.result.ResultUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Deacription 权限验证
 * @Author zl
 * @Date 2022/4/10 21:38
 * @Version 1.0
 **/
@Component
@Slf4j
public class AuthCheckPermissionHandlerInterceptor implements AsyncHandlerInterceptor {
    @Autowired
    private AuthUserService authUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //静态资源绕过
        if (handler instanceof ResourceHttpRequestHandler) {
            return true;
        }
        //获取权限验证注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        AuthCheckPermission authCheckPermission = handlerMethod.getMethodAnnotation(AuthCheckPermission.class);
        if (authCheckPermission == null) {
            return true;
        }
        String permission = authCheckPermission.value();
        AuthCheckPermissionParameter checkPermissionParameter = SpringUtil.getBean(AuthCheckPermissionParameter.class);
        List<String> permissions = checkPermissionParameter.getPermissions();
        if (!isPermission(permission, permissions)) {
            Result result = ResultUtils.notAuthority("权限不足:" + permission);
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(result));
            writer.flush();
            return false;
        }
        return true;
    }

    private boolean isPermission(String permission, List<String> permissions) {
        String[] temps = permission.split(",");
        for (String temp : temps) {
            if (permissions.contains(temp)) {
                return true;
            }
        }
        return false;
    }
}
